import { defineStore } from 'pinia'
import { RoutesType } from '@/store/modules/routes/type'
import { RouteRecordRaw, Router } from 'vue-router'
import { lStorage } from '@/utils/storage'

// 自动注册全局组件（懒加载模式）
const modules = import.meta.glob('../../../views/**/*.vue')

interface RoutesState {
  routes: RoutesType[]
  addedRouteNames: string[]
  isRoutesLoaded: boolean
}

export const useRoutesStore = defineStore('routesStore', {
  state: (): RoutesState => ({
    routes: [],
    addedRouteNames: [],
    isRoutesLoaded: false,
  }),

  getters: {
    // 获取所有路由名称
    routeNames: (state) => state.addedRouteNames,

    // 获取所有路由路径
    routePaths: (state) => state.routes.map((route) => route.path),

    // 获取路由加载状态
    routesLoaded: (state) => state.isRoutesLoaded,
  },

  actions: {
    /**
     * 初始化路由
     * @param router 路由实例
     */
    async initRoutes(router: Router) {
      try {
        const cachedRoutes = lStorage.get<RoutesType[]>('WXAI_USER_ROUTES')
        if (cachedRoutes) {
          await this.addRoutes(cachedRoutes, router)
        }
      } catch (error) {
        console.error('初始化路由失败:', error)
        throw error
      }
    },

    /**
     * 动态添加路由
     * @param data 动态路由数据
     * @param router 路由实例
     */
    async addRoutes(data: RoutesType[], router: Router) {
      try {
        // 每次调用都更新本地存储和状态
        lStorage.set('WXAI_USER_ROUTES', data)
        this.routes = data
        this.isRoutesLoaded = false

        // 清理之前添加的路由
        await this.clearAddedRoutes(router)

        // 解析路由并记录名称
        const { routes: parsedRoutes, names } = this.parseRoutes(data)
        this.addedRouteNames = names

        // 添加动态路由到父路由下
        for (const route of parsedRoutes) {
          router.addRoute('layout', route)
        }

        // 添加全局404路由（确保最后添加）
        if (!router.hasRoute('not-found')) {
          router.addRoute({
            path: '/:pathMatch(.*)*',
            name: 'not-found',
            component: () => import('@/page/error/404.vue'),
          })
        }

        // 标记路由加载完成
        this.isRoutesLoaded = true
      } catch (error) {
        console.error('添加动态路由失败:', error)
        this.isRoutesLoaded = false
        throw error
      }
    },

    /**
     * 清理已添加的路由
     * @param router 路由实例
     */
    async clearAddedRoutes(router: Router) {
      try {
        for (const name of this.addedRouteNames) {
          if (router.hasRoute(name)) {
            router.removeRoute(name)
          }
        }
        this.addedRouteNames = []
      } catch (error) {
        console.error('清理路由失败:', error)
        throw error
      }
    },

    /**
     * 解析动态路由
     * @param routesData 路由数据
     * @returns 解析后的路由数组和收集的路由名称
     */
    parseRoutes(routesData: RoutesType[]): {
      routes: RouteRecordRaw[]
      names: string[]
    } {
      const addedNames: string[] = []

      const parsed = routesData
        .map((item: RoutesType) => {
          // 处理组件路径
          const componentLoader = this.resolveComponentLoader(item.component)

          // 检查组件有效性
          if (!componentLoader && !item.children?.length) {
            console.warn(`路由组件未找到: ${item.path} -> ${item.component}`)
            return null
          }

          // 处理子路由
          const childrenResult = item.children
            ? this.parseRoutes(item.children)
            : null
          if (childrenResult && childrenResult.routes.length === 0) return null

          // 收集路由名称
          if (item.name) addedNames.push(item.name as string)

          // 构造路由对象
          return {
            ...item,
            component: componentLoader
              ? () =>
                componentLoader().catch(() => import('@/page/error/404.vue'))
              : undefined,
            children: childrenResult?.routes,
          } as RouteRecordRaw
        })
        .filter(Boolean) as RouteRecordRaw[]

      return { routes: parsed, names: addedNames }
    },

    /**
     * 解析组件加载器
     * @param component 组件配置
     * @returns 组件加载器函数
     */
    resolveComponentLoader(component: any): (() => Promise<any>) | undefined {
      if (typeof component === 'function') {
        return component
      }

      if (typeof component === 'string') {
        const normalizedPath = component.startsWith('/')
          ? `../../../views${component}.vue`
          : `../../../views/${component}.vue`

        return modules[normalizedPath]
      }

      return undefined
    },

    /**
     * 清除动态路由
     * @param router 路由实例
     */
    async clearRoutes(router: Router) {
      try {
        await this.clearAddedRoutes(router)
        this.routes = []
        this.isRoutesLoaded = false
        lStorage.remove('WXAI_USER_ROUTES')
      } catch (error) {
        console.error('清除路由失败:', error)
        throw error
      }
    },
  },
})
